package com.bootdo.mq;

import java.util.HashMap;
import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.config.Constant;
import com.bootdo.common.configure.dao.DictDao;
import com.bootdo.common.configure.domain.DictDO;
import com.bootdo.payee.dao.PayeeDao;
import com.bootdo.payee.domain.PayeeDO;

/**
 * @program: bootdo
 * @packageName: com.bootdo.mq
 * @className: InitQueueBeforeStart
 * @description: 程序启动时初始化所有渠道
 * @create: 2020-03-15 22:30
 */
@Component
public class InitQueueBeforeStart {

    @Autowired
    private PayeeDao payeeMapper;

    @Autowired
    private RabbitUtil rabbitUtil;

    @Autowired
    private DictDao dictMapper;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //为防止MQ中无对应渠道而到导致报错，每次启动时初始化渠道
    @PostConstruct
    public void initQueue(){

        DictDO dictDO = new DictDO();
        dictDO.setType("isInit");
        dictDO.setIsShow(1);

        dictDO = dictMapper.getDictByType(dictDO);

        logger.debug("判断是否开启初始化队列"+JSONObject.toJSONString(dictDO));
        if (dictDO==null || "0".equals(dictDO.getValue())){
            List<PayeeDO> list = payeeMapper.list(new HashMap<>());
            for (PayeeDO payee: list) {
                String queueName = "topic.payee.user_"+payee.getUserId();
                Queue queue = new Queue(queueName,true);
                rabbitUtil.addQueue(queue);
            }
            Queue changQ = new Queue(Constant.CHANG_SORT,true);
            rabbitUtil.addQueue(changQ);

            Queue checkQ = new Queue(Constant.RECIVE_HEART,true);
            rabbitUtil.addQueue(checkQ);

            Queue quotaQ = new Queue(Constant.UPDATE_QUOTA,true);
            rabbitUtil.addQueue(quotaQ);
        }

        if (dictDO!=null) {
            dictDO.setValue("1");
            dictMapper.update(dictDO);
        } else {
            dictDO = new DictDO();
            dictDO.setValue("1");
            dictDO.setType("isInit");
            dictDO.setIsShow(1);
            dictDO.setDescription("开启初始化MQ队列");
            dictDO.setName("开启初始化MQ队列");
            dictMapper.save(dictDO);
        }
    }

}
